package com.hankol.feature_wine_meal

import android.text.TextUtils
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Route
import com.baselibrary.extension.checkNotNull
import com.baselibrary.extension.checkValue
import com.baselibrary.extension.toast
import com.baselibrary.manager.LoadingManager
import com.baselibrary.router.ActivityRouter
import com.baselibrary.utils.*
import com.bumptech.glide.Glide
import com.baselibrary.activity.BaseActivity
import com.hankol.feature_wine_meal.adapter.ShareWineMealPosterAdapter
import com.hankol.feature_wine_meal.api.OnUpPosterCallBack
import com.hankol.feature_wine_meal.api.WineMealHelp
import com.hankol.feature_wine_meal.databinding.ActivityWineMealPosterBinding
import com.hankol.feature_wine_meal.viewmodel.WineMealViewModel
import com.transitionseverywhere.TransitionManager
import com.umeng.socialize.bean.SHARE_MEDIA
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.async
import kotlinx.coroutines.runBlocking
import java.io.File

/**
 * @description 下酒菜海报
 * @author 关忆北、
 * @time 2022/6/30 9:58 下午
 */
@Route(path = ActivityRouter.WINE_MEAL.WINE_MEAL_POSTER)
class WineMealPosterActivity : BaseActivity(), OnUpPosterCallBack {
    private val mWineMealHelp = ActivityRouter.getARouterInterface<WineMealHelp>(ActivityRouter.WINE_MEAL.WINE_MEAL_HELP)

    companion object {
        const val WINE_MEA_POSTER_FATHER: Float = 310f / 452f//视觉搞的宽高
        const val WINE_MEA_POSTER_SON: Float = 294f / 200f//视觉搞的宽高
        const val WINE_MEA_NAME = "WINE_MEA_NAME"
        const val WINE_MEA_DES = "WINE_MEA_DES"
        const val WINE_MEA_COVER = "WINE_MEA_COVER"
        const val WINE_MEA_ID = "WINE_MEA_ID"
        const val WINE_MEA_AUTHOR_NAME = "WINE_MEA_AUTHOR_NAME"
        const val WINE_MEA_AUTHOR_HEAD = "WINE_MEA_AUTHOR_HEAD"
    }

    private lateinit var dataBinding: ActivityWineMealPosterBinding
    private lateinit var mViewModel: WineMealViewModel
    private var isPreserve: Boolean = false
    private var filePath: String = ""
    private var foodName: String = ""
    private var foodDes: String = ""
    private var foodCover: String = ""
    private var authorName: String = ""
    private var authorHead: String = ""
    private var foodId: Long = 0
    private var position: Int = -1
    override fun getLayoutId(): Int {
        initImmersion(true)
        return R.layout.activity_wine_meal_poster
    }

    override fun init() {
        intent.extras?.let {
            foodName = it.getString(WINE_MEA_NAME).checkValue()
            authorHead = it.getString(WINE_MEA_AUTHOR_HEAD).checkValue()
            foodDes = it.getString(WINE_MEA_DES).checkValue()
            foodCover = it.getString(WINE_MEA_COVER).checkValue()
            foodId = it.getLong(WINE_MEA_ID)
            authorName = it.getString(WINE_MEA_AUTHOR_NAME).checkValue()
        }
        dataBinding = getDataBinding<ActivityWineMealPosterBinding>()
        mViewModel = getActivityViewModelProvider(this).get(WineMealViewModel::class.java)
        //加载背景图
        Glide.with(applicationContext).load(foodCover).placeholder(com.baselibrary.R.drawable.ic_def_hanxiang_228).apply(dataBinding.ivWineMealPosterBg.setGaussBlur()).into(dataBinding.ivWineMealPosterBg)

        //最外层view，记录两边33dp后view的宽
        val fatherViewWidth = ScreenUtils.getScreenWidth() - ScreenUtils.dip2px(applicationContext, 64f)
        val sonViewWidth = fatherViewWidth - ScreenUtils.dip2px(applicationContext, 16f)//两边8dp
        mViewModel.upPosterView(dataBinding, fatherViewWidth, sonViewWidth)
        dataBinding.tvWinePosterFoodName.paint.isFakeBoldText = true
        setView()
        initListener()

    }

    fun initListener() {
        dataBinding.imgCancel.setOnClickListener { finish() }
    }

    fun setView() {
        dataBinding.tvWinePosterFoodDes.text = foodDes
        dataBinding.tvWinePosterFoodName.text = foodName
        dataBinding.tvPosterName.text = authorName
        GlideUtils.loadImg_228(applicationContext, foodCover, dataBinding.roundCover)
        GlideUtils.loadUserHead(applicationContext, authorHead, dataBinding.circleHead)
        dataBinding.ivWinePosterCode.setImageBitmap(mViewModel.createQRCode(applicationContext, mWineMealHelp.getShareUrl() + foodId))
        loadData()
    }

    override fun onSuccess(URL: String, filePath: String) {
        this.filePath = filePath
        share()
    }

    override fun onFail() {

    }


    private fun loadData() {
        TransitionManager.beginDelayedTransition(dataBinding.llWineMealPoster)
        dataBinding.llShare.visibility = View.VISIBLE
        dataBinding.rvWineMealPosterLayout.layoutManager = LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false)
        val mSharePosterAdapter = ShareWineMealPosterAdapter()
        dataBinding.rvWineMealPosterLayout.adapter = mSharePosterAdapter

        mSharePosterAdapter.setListener { position ->
            this.position = position
            if (filePath.checkNotNull()) {
                //已经生成过
                share()
            } else {
                dataBinding.rlWinePoster.post {
                    mViewModel.createHaiBao(this@WineMealPosterActivity, dataBinding, this@WineMealPosterActivity)
                }
            }

        }
        try {
            runBlocking {
                val HBCtrip = GlobalScope.async {
                    val bitmap = BitmapUtils.convertViewToBitmap(dataBinding.rlWinePoster);
                    val createPosterFile = FileUtils.createPosterFile()
                    FileUtils.compressBmpToFile4Fixed(bitmap, createPosterFile, 50)
                    filePath = createPosterFile.absolutePath.checkValue()
                }
            }
        } catch (e: Exception) {
            LoadingManager.hideLoadingDialog(this)
            "网络异常，请稍后再试".toast()
            e.message
        }
    }

    fun share() {
        if (position != 2) {
            UMShareUtils.shareImageLocalFile(this, if (position == 0) SHARE_MEDIA.WEIXIN else SHARE_MEDIA.WEIXIN_CIRCLE, filePath)
        } else {
            if (!TextUtils.isEmpty(filePath)) {
                if (!DoubleClickHelper.isOnDoubleClick()) {
                    StorageUtils.saveImageToGallery(this, filePath, object : StorageUtils.ISaveCallback {
                        override fun saveSuccess() {
                            isPreserve = true
                            dataBinding.rlWinePoster.postDelayed(Runnable {
                                LoadingManager.hideLoadingDialog(this@WineMealPosterActivity)
                                ToastUtils.showShort(this@WineMealPosterActivity, "海报已下载到相册")
                            }, 200)
                        }
                    })
                }
            }
        }
    }

    override fun onDestroy() {
        if (!isPreserve) {
            if (filePath.isNotEmpty()) {
                File(filePath).delete()
            }
        }
        super.onDestroy()
    }
}